package com.labofjet.web.bean.impl;

import java.io.IOException;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.labofjet.web.bean.ContextDTO;

/**
 * 利用jackson转化post上来的字符串到contextDTO,目前只支持ajax,form还没支持
 * 
 * @author jyzjyz12@163.com
 * 
 */
public class ContextHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    public static final Charset UTF8;
    private static final ObjectMapper OM;
    static {
        UTF8 = Charset.forName("UTF-8");
        OM = new ObjectMapper();
        OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);// java没有json的某些字段不报错
    }

    /**
     * Instantiates a new context http message converter.
     */
    public ContextHttpMessageConverter() {
        super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    /**
     * 将ajax上传数据放到ContextDTO的root里.现在还不确定要转化成什么javaType
     */
    @Override
    protected ContextDTO readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException,
            HttpMessageNotReadableException {
        JsonContextDTO dto = new JsonContextDTO();
        JsonNode root = OM.readTree(inputMessage.getBody());
        dto.setRootNode(root);
        return dto;
    }

    /**
     * 将ContextDTO数据转化成json输出给JS
     */
    @Override
    protected void writeInternal(Object context, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {
        OM.writeValue(outputMessage.getBody(), context);
    }
}
